<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\GoodsClass;
use App\Models\GoodsNexus;
use Dotenv\Validator;
use Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Pagination\LengthAwarePaginator;

class CommodityController extends Controller {
    /*
     * @商品管理的首页
     */

    public function index(Request $request) {
        $search = $request->input('search');
        $page = $request->has('page') ? $request->input('page') : 1;
        $limit = 15;
        if ($request->has('search')) {
            $search = $request->input('search');
            $count = Goods::where('name', 'like', '%' . $search . '%')->count();
        } else {
            $count = Goods::count(); //总数
        }
        $total_page = ceil($count / $limit);
        $offset = ($limit * $page) - $limit;
        if ($request->has('search')) {
            $search = $request->input('search');
            $goods = Goods::where('name', 'like', '%' . $search . '%')->offset($offset)->limit($limit)->with('goodsclass', 'goodsNexus')->get();
        } else {
            $goods = Goods::with('goodsclass', 'goodsNexus')->offset($offset)->limit($limit)->get();
        }
        $data = [];
        foreach ($goods as $key => $v) {
            $data[$key]['id'] = $v->id;
            $data[$key]['name'] = $v->name;
            $data[$key]['product_code'] = $v->product_code;
            $data[$key]['class_name'] = isset($v->goodsclass->class_name) ? $v->goodsclass->class_name : '未分类';
            $data[$key]['nums'] = $v->goodsNexus->count();
            $data[$key]['price'] = $v->price;
        }
//dd($data);
        //return 'test';
        $goods = new LengthAwarePaginator($data, $count, $limit, $page, ['path' => '/admin/commodity']);

        $goodsClasses = getTree(GoodsClass::all()->toArray());
        return view("admin.commodity", [
            'goodsClasses' => $goodsClasses,
            'goods' => $goods,
            'search' => $search,
            'total_page' => $total_page
        ]);
    }

    /*
     * @=========================商品管理的查看页面===================================
     */

    public function show($id) {
        $goods = Goods::select('goods.*')->where('goods.id', '=', $id)->get();
        $data = [];
        foreach ($goods as $key => $v) {
            $data[$key]['id'] = $v->id;
            $data[$key]['name'] = $v->name;
            $data[$key]['product_code'] = $v->product_code;
            $data[$key]['class_name'] = isset($v->goodsclass->class_name) ? $v->goodsclass->class_name : '未分类';
            $data[$key]['nums'] = $v->goodsNexus->count();
            $data[$key]['price'] = $v->price;
            $data[$key]['goods_info'] = $v->goods_info;
            $data[$key]['img'] = $v->img;
            $data[$key]['site'] = $v->site;
            $data[$key]['work_company'] = $v->work_company;
            $data[$key]['status'] = $v->status;
            $data[$key]['area'] = $v->area;
            $data[$key]['product_at'] = $v->product_at;
            $data[$key]['created_at'] = $v->created_at;
            $data[$key]['productdate'] = $v->productdate;
        }
        $datas = $data;
        //rfid码的售卖情况
        $paginate = 5;
        $rfid_lists = Goods::join('goods_nexus', 'goods_nexus.goods_id', '=', 'goods.id')
                ->select('goods_nexus.*', 'goods.id')
                ->where('goods_nexus.goods_id', '=', $id)
                ->paginate($paginate);
        $count = Goods::join('goods_nexus', 'goods_nexus.goods_id', '=', 'goods.id')
                        ->select('goods_nexus.*', 'goods.id')
                        ->where('goods_nexus.goods_id', '=', $id)->count(); //总数
        $total_page = ceil($count / $paginate); //共多少页
        $goodsClasses = getTree(GoodsClass::all()->toArray());
        $targetGoods = Goods::find($id);
        $targetClassId = isset($targetGoods->goodsClass->id) ? $targetGoods->goodsClass->id : '';
        return view("admin.commodity_edit", [
            'goodsClasses' => $goodsClasses,
            'targetClassId' => $targetClassId,
            'datas' => $datas[0],
            'rfid_lists' => $rfid_lists,
            'total_page' => $total_page
        ]);
    }

    /*
     * =========================@商品管理的修改==============================
     */

    public function update(Request $request, $id) {
//         dd($request->all());
        $goods = Goods::find($id);
//		dd($goods);
        if ($request->isMethod('post')) {
            $roles = [
                'name' => 'required',
                'product_at' => 'date',
                'productdate' => 'min:1|max:200',
//				'work_company' => 'required|min:1|max:200',
                //'site' => 'required',
                'product_code' => 'required',
                'price' => 'required|min:0',
            ];
            $messages = [
                'required' => ':attribute为必填项',
                'min' => ':attribute最小不符合要求',
                'date' => ':attribute日期格式不正确',
                'max' => ':attribute最大不符合要求',
                'integer' => ':attribute为整数',
            ];
            $chinese = [
                'name' => '商品名称',
                'area' => '产地',
                'product_at' => '生产日期',
                'productdate' => '保质期',
                'work_company' => '加工企业',
                'site' => '产址',
                'price' => '商品单价',
            ];
            $validator = \Validator::make($request->all(), $roles, $messages, $chinese);
            if ($validator->fails()) {
                $error = $validator->errors()->all();
                return ['status' => 0, 'msg' => $error[0]];
            }
            /* ================上传图片=========================== */
            $file = $request->file('img');
            if ($request->hasFile('img') && $file->isValid()) {
                $filePath = public_path() . '\uploads\\' . $goods->img;
                if (is_file($filePath)) {
                    unlink($filePath);
                }
                // 获取文件相关信息
                $originalName = $file->getClientOriginalName(); // 文件原名
                $ext = $file->getClientOriginalExtension(); // 扩展名
                $realPath = $file->getRealPath(); //临时文件的绝对路径
                $type = $file->getClientMimeType(); // image/jpeg
                // 上传文件
                $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
                // 使用我们新建的uploads本地存储空间（目录）
                $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
                $goods->img = 'uploads/' . $filename;
            }
            $class_id = $request->get('class_id');
            $name = $request->get('name');
            $area = $request->get('area') ? $request->get('area') : '';
            $product_at = $request->get('product_at') ? $request->get('product_at') : date('Y-m-d');
            $productdate = $request->get('productdate') ? $request->get('productdate') : date('Y-m-d');
            $work_company = $request->get('work_company') ? $request->get('work_company') : '';
            $site = $request->get('site') ? $request->get('site') : '';
            $price = $request->get('price');
            if ($price < 0) {
                return ['status' => 0, 'msg' => '商品价格不可为负'];
            }
            $product_code = $request->get('product_code');
            $res = Goods::where('product_code', '!=', $goods->product_code)->where('product_code', $product_code)->first();
            if ($res) {
                return ['status' => 0, 'msg' => '该商品编号已经存在'];
            }
            $goods->product_code = $product_code;
            $goods->class_id = $class_id;
            $goods->name = $name;
            $goods->area = $area;
            $goods->product_at = $product_at;
            $goods->productdate = $productdate;
            $goods->work_company = $work_company;
            $goods->site = $site;
            $goods->price = $price;
            $goods->save();
            return ['status' => 1, 'msg' => '添加成功'];
        }
    }

    /*
     * @===================商品管理的添加==================================
     */

    public function store(Request $request) {
        $roles = [
            'goods_name' => 'required',
            'goods_code' => 'required',
            'goods_price' => 'required|min:1',
            'goods_img' => 'required',
        ];
        $messages = [
            'required' => ':attribute为必填项',
            'min' => ':attribute为正整数',
            'integer' => ':attribute为必须是整数',
        ];
        $chinese = ['goods_name' => '商品名称',
            'goods_code' => '商品编号',
//				'goods_num' => '商品数量',
            'goods_price' => '商品单价',
            'goods_img' => '商品图片',
        ];
        $validator = \Validator::make($request->all(), $roles, $messages, $chinese);
        if ($validator->fails()) {
            $error = $validator->errors()->all();
            return ['status' => 0, 'msg' => $error[0]];
        }
        //图片的验证
        $goods = new Goods();
        $file = $request->goods_img;
        if ($file->isValid()) {
            // 获取文件相关信息
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension(); // 扩展名
            $realPath = $file->getRealPath(); //临时文件的绝对路径
            $type = $file->getClientMimeType(); // image/jpeg
            // 上传文件
            $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
            // 使用我们新建的uploads本地存储空间（目录）
            $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
        }
        $class = $request->class_id;
        $name = $request->goods_name;
        $res = Goods::where('name', '=', $name)->first();
        if ($res) {
            return ['status' => 0, 'msg' => '该商品名称已经存在'];
        }
        $product_code = $request->goods_code;
        $res = Goods::where('product_code', '=', $product_code)->first();
        if ($res) {
            return ['status' => 0, 'msg' => '该商品编号已经存在'];
        }
        $price = $request->goods_price;
        if ($price < 0) {
            return ['status' => 0, 'msg' => '价格为正数'];
        }
        $goods->class_id = $class;
        $goods->img = 'uploads/' . $filename;
        $goods->name = $name;
        $goods->product_code = $product_code;
        $goods->price = $price;
        $goods->save();
        return ['status' => 1, 'msg' => '添加成功'];
    }

    /*
     *  * @=============================商品管理的商品删除======================
     */

    public function destroy($id) {
        $goods = Goods::find($id);
        if ($goods->delete()) {
            return redirect('admin/commodity');
        } else {
            return redirect()->back();
        }
    }

    /*
     * @商品管理之商品是否上下架
     */

    public function status(Request $request) {
        $is_show = $request->is_show;
        $id = $request->goods_id;
        //var_dump($is_show);die;
        if ($is_show == 1) {
            $is_show = 0;
        } else {
            $is_show = 1;
        }
        $res = Goods::find($id)
                ->update(['status' => $is_show]);

        return $is_show;
    }

    /*
     * @导入商品excel
     * 现在要下载的文件保存在public/leading
     * 以前的public/goods.xlsx是商品管理的导入
     * 以前的public/rfid.xlsx是商品管理中的商品详情的RFID列表的导入
     */

    public function import(Request $request) {
//	    dd($request->all());
        //laravel excel的两种写法之一,注意作用域链

        $reader = Excel::selectSheetsByIndex(0)->load($request->file('excel'));
        $mapData = $reader->get(['商品分类的id', '商品名称', '商品编号', '单价'])->toArray();
        if (empty($mapData[0])) {
            return ['status' => 0, 'msg' => 'excel数据格式不正确!'];
        }
        //商品分类不能为空
        $mapData = filter_array(filter_array($mapData));
        foreach ($mapData as $v) {
            if (!isset($v['商品分类的id']) || !isset($v['商品名称']) || !isset($v['商品编号']) || !isset($v['单价'])) {
                return ['status' => 0, 'msg' => '商品分类的id、商品名称、商品编号、单价为必填字段!'];
            }
        }
        foreach ($mapData as $key => $v) {
            $mapData[$key]['商品编号'] = str_replace(' ', '', $mapData[$key]['商品编号']);
        }
        $colData = [array_column($mapData, '商品名称'), array_column($mapData, '商品编号')];
        foreach ($colData as $col) {
            if (count($col) != count(array_unique($col))) {
                $sameValues = array_diff_assoc($col, array_unique($col));
                $sameValuesStr = implode(';', $sameValues);
                return ['status' => 0, 'msg' => 'excel中商品名称、商品编号不能重复!重复信息:'.$sameValuesStr,'sameValues'=>$sameValues];
            }
        }
        foreach ($colData[0] as $col) {
            if (Goods::where('name', $col)->exists()) {
                return ['status' => 0, 'msg' => 'excel中有已经存在的商品名称!'];
            }
        }
        foreach ($colData[1] as $col) {
            if (Goods::where('product_code', $col)->exists()) {
                return ['status' => 0, 'msg' => 'excel中有已经存在的商品编号!'];
            }
        }

        //判断表头的数据是非正确,防止其他文件的导入
        $data = $reader->get();
        //数据通过models传到数据库中
        foreach ($data as $rfidData) {
            Goods::create([
                'class_id' => $rfidData['商品分类的id'],
                'name' => $rfidData['商品名称'],
                'goods_info' => $rfidData['商品信息'],
                'img' => $rfidData['商品图片'],
                'product_code' => str_replace(' ', '', $rfidData['商品编号']),
                'site' => $rfidData['产址'],
                'work_company' => $rfidData['加工企业'],
                'productdate' => $rfidData['保质期'],
                'area' => $rfidData['产地'],
                'price' => $rfidData['单价'],
                'product_at' => $rfidData['生产日期'],
            ]);
        }
        return ['status' => 1, 'msg' => '导入成功!'];
    }

    /*
     * @模板下载
     * 现在要下载的文件保存在public/leading
     * 以前的public/goods.xlsx是商品管理的导入
     * 以前的public/rfid.xlsx是商品管理中的商品详情的RFID列表的导入
     */

    public function download() {
        return response()
                        ->download(realpath(base_path('public')) . '/goods.xlsx', "商品导入表" . '.xlsx');
    }

    /*
     * ********@@@商品详情导入rfid***********
     * 现在要下载的文件保存在public/leading
     * 以前的public/goods.xlsx是商品管理的导入
     * 以前的public/rfid.xlsx是商品管理中的商品详情的RFID列表的导入
     */

    public function rfidimport(Request $request, $id) {
//	    dd($request->all());
        $data = Excel::load($request->file('excel'), function($reader) {
                    
                })->get()->toArray();
        //商品分类不能为空
//        dd($data);
        $sh_array = array();
        foreach ($data[0] as $ite) {
            reset($ite);
            $first = current($ite);
            array_push($sh_array, $first);
        }
//        dd($sh_array);
        foreach ($sh_array as $v) {
            if (empty($v)) {
                return response()->json(['status' => 0, 'msg' => '商品序号不能为空']);
            }
        }

        $xh_array = array();
        foreach ($data[0] as $itee) {
            reset($itee);
            current($itee);
            $secnd = next($itee);
            array_push($xh_array, $secnd);
        }
//        dd($xh_array);
        foreach ($xh_array as $v) {
            if (empty($v)) {
                return response()->json(['status' => 0, 'msg' => 'rfid不能为空']);
            }
        }

//        dd($data);
        $ch_array = array();
        foreach ($data[0] as $item) {
            reset($item);
            current($item);
            $first = next($item);
            array_push($ch_array, $first);
        }
        //判断导入的数据是非有重复值
        if (count($ch_array) != count(array_unique($ch_array))) {
            return response()->json(['status' => 0, 'msg' => '该导入数组有重复值']);
        }
        //导入的数据与数据库的数据是否重复
        $warehouses = GoodsNexus::where('rfid', '=', $ch_array[0])->first();
        if ($warehouses) {
            return response()->json(['status' => 0, 'msg' => '导入失败,rfid码重复']);
        }
        foreach ($data as $value) {//循环sheet
            if (!empty($value)) {
                $titleArr = array_keys($value[0]);
                //判断表头的数据是非正确,防止其他文件的导入
                if ($titleArr[0] != '商品序号') {
                    return response()->json(['status' => 0, 'msg' => '导入失败']);
                }
                if ($titleArr[1] != 'rfid码') {
                    return response()->json(['status' => 0, 'msg' => '导入失败']);
                }
            }
            //数据通过models传到数据库中
            foreach ($value as $rfidData) {
                GoodsNexus::create([
                    'goods_id' => $rfidData['商品序号'],
                    'rfid' => $rfidData['rfid码'],
                ]);
            }
        }
        return ['status' => 1, 'msg' => '导入成功'];
    }

    public function rfiddownload() {
        return response()
                        ->download(realpath(base_path('public')) . '/rfid.xlsx', "rfid码导入表" . '.xlsx');
    }

}
